// estore/service/ReportService.java
package com.estore.service;

import com.estore.model.*;
import java.time.LocalDate;
import java.util.*;

public class ReportService {
    private final OrderService orderService;
    private ProductService productService;
    private UserService userService;

    public ReportService(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 获取销售数据统计报告
     * @param orderService 开始日期
     * @return 销售统计数据
     */
    // 在 ReportService.java 中修改构造函数
public ReportService(OrderService orderService, ProductService productService, UserService userService) {
    this.orderService = orderService;
    this.productService = productService;
    this.userService = userService;
}

    public SalesReport generateSalesReport(LocalDate startDate, LocalDate endDate) {
        List<Order> orders = orderService.getAllOrders();

        // 过滤指定时间段内的订单
        List<Order> filteredOrders = orders.stream()
            .filter(order -> {
                LocalDate orderDate = order.getCreateTime().toLocalDate();
                return !orderDate.isBefore(startDate) && !orderDate.isAfter(endDate);
            })
            .toList();

        // 统计总销售额和订单数量
        double totalRevenue = 0.0;
        int totalOrders = filteredOrders.size();
        Map<String, Integer> categorySales = new HashMap<>();
        Map<String, Double> productSales = new HashMap<>();

        for (Order order : filteredOrders) {
            totalRevenue += order.getTotalPrice();

            // 统计各类别销量
            for (Map.Entry<String, Integer> item : order.getItems().entrySet()) {
                String productId = item.getKey();
                Integer quantity = item.getValue();

                Product product = productService.findProductById(productId);
                if (product != null) {
                    // 分类销量统计
                    String categoryName = product.getCategory() != null ? product.getCategory() : "未分类";
                    categorySales.merge(categoryName, quantity, Integer::sum);

                    // 商品销量统计
                    String productName = product.getName();
                    productSales.merge(productName, quantity * product.getPrice(), Double::sum);
                }
            }
        }

        return new SalesReport(totalRevenue, totalOrders, categorySales, productSales);
    }

    /**
     * 获取用户行为分析报告
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 用户行为分析数据
     */
 // 在 ReportService.java 中修改 generateUserBehaviorAnalysis 方法
public UserBehaviorAnalysis generateUserBehaviorAnalysis(LocalDate startDate, LocalDate endDate) {
    List<Order> orders = orderService.getAllOrders();

    // 过滤指定时间段内的订单
    List<Order> filteredOrders = orders.stream()
        .filter(order -> {
            LocalDate orderDate = order.getCreateTime().toLocalDate();
            return !orderDate.isBefore(startDate) && !orderDate.isAfter(endDate);
        })
        .toList();

    // 统计活跃用户数
    Set<String> activeUsers = new HashSet<>();
    // 统计平均订单金额
    double totalRevenue = 0.0;
    int totalOrders = 0;
    // 统计热门商品
    Map<String, Integer> popularProducts = new HashMap<>();
    // 统计购买频次分布
    Map<Integer, Integer> purchaseFrequencyDistribution = new HashMap<>();

    for (Order order : filteredOrders) {
        activeUsers.add(order.getUserId());
        totalRevenue += order.getTotalPrice();
        totalOrders++;

        // 计算每个用户的购买频次
        purchaseFrequencyDistribution.merge(
            purchaseFrequencyDistribution.getOrDefault(order.getUserId(), 0) + 1,
            1,
            Integer::sum
        );

        // 热门商品统计
        for (Map.Entry<String, Integer> item : order.getItems().entrySet()) {
            String productId = item.getKey();
            Integer quantity = item.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                popularProducts.merge(product.getName(), quantity, Integer::sum);
            } else {
                popularProducts.merge(productId, quantity, Integer::sum);
            }
        }
    }

    // 计算平均订单金额
    double averageOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0.0;

    return new UserBehaviorAnalysis(
        activeUsers.size(),
        averageOrderValue,
        totalOrders,
        popularProducts,
        purchaseFrequencyDistribution
    );
}


    /**
     * 获取商品销售排行榜
     * @param limit 排行榜大小
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 商品销售排行榜
     */
// 在 ReportService.java 中修改 getProductSalesRanking 方法
public List<ProductRanking> getProductSalesRanking(int limit, LocalDate startDate, LocalDate endDate) {
    List<Order> orders = orderService.getAllOrders();

    // 过滤指定时间段内的订单
    Map<String, Integer> productQuantityMap = new HashMap<>();

    for (Order order : orders) {
        LocalDate orderDate = order.getCreateTime().toLocalDate();
        if (!orderDate.isBefore(startDate) && !orderDate.isAfter(endDate)) {
            for (Map.Entry<String, Integer> item : order.getItems().entrySet()) {
                String productId = item.getKey();
                Integer quantity = item.getValue();
                productQuantityMap.merge(productId, quantity, Integer::sum);
            }
        }
    }

    // 转换为列表并排序
    List<Map.Entry<String, Integer>> sortedEntries = productQuantityMap.entrySet()
        .stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
        .limit(limit)
        .toList();

    List<ProductRanking> rankings = new ArrayList<>();
    for (int i = 0; i < sortedEntries.size(); i++) {
        Map.Entry<String, Integer> entry = sortedEntries.get(i);
        Product product = productService.findProductById(entry.getKey());
        String productName = entry.getKey();
        if (product != null) {
            productName = product.getName();
        }
        rankings.add(new ProductRanking(
            i + 1,
            entry.getKey(),
            productName,
            entry.getValue(),
            product != null ? product.getPrice() * entry.getValue() : 0.0
        ));
    }

    return rankings;
}


    /**
     * 生成财务报表
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 财务报表数据
     */
// 在 ReportService.java 中修改 generateFinancialReport 方法
public FinancialReport generateFinancialReport(LocalDate startDate, LocalDate endDate) {
    List<Order> orders = orderService.getAllOrders();

    // 过滤指定时间段内的订单
    List<Order> filteredOrders = orders.stream()
        .filter(order -> {
            LocalDate orderDate = order.getCreateTime().toLocalDate();
            return !orderDate.isBefore(startDate) && !orderDate.isAfter(endDate);
        })
        .toList();

    // 按月统计收入
    Map<String, MonthlyIncome> monthlyIncome = new HashMap<>();

    // 总收入和成本
    double totalRevenue = 0.0;
    double totalCost = 0.0;
    double netProfit;

    // 各类别收入
    Map<String, Double> categoryRevenue = new HashMap<>();

    for (Order order : filteredOrders) {
        double orderRevenue = order.getTotalPrice();
        totalRevenue += orderRevenue;

        // 计算成本（简单示例：假设每件商品成本是售价的60%）
        double cost = orderRevenue * 0.6;
        totalCost += cost;

        // 统计各类别收入
        for (Map.Entry<String, Integer> item : order.getItems().entrySet()) {
            String productId = item.getKey();
            Product product = productService.findProductById(productId);
            if (product != null) {
                String categoryName = "未分类";
                if (product.getTags() != null && !product.getTags().isEmpty()) {
                    categoryName = product.getTags().iterator().next();
                }
                categoryRevenue.merge(categoryName, orderRevenue, Double::sum);
            }
        }

        // 按月份统计收入
        LocalDate orderDate = order.getCreateTime().toLocalDate();
        String monthKey = orderDate.getYear() + "-" + String.format("%02d", orderDate.getMonthValue());
        monthlyIncome.computeIfAbsent(monthKey, MonthlyIncome::new).addIncome(orderRevenue);
    }

    netProfit = totalRevenue - totalCost;

    return new FinancialReport(
        startDate,
        endDate,
        totalRevenue,
        totalCost,
        netProfit,
        monthlyIncome.values().stream().toList(),
        categoryRevenue
    );
}


    /**
     * 获取最近7天销售趋势
     * @return 最近7天销售趋势数据
     */
    public List<DailySalesTrend> getRecent7DaysSalesTrend() {
        List<DailySalesTrend> trendList = new ArrayList<>();
        LocalDate today = LocalDate.now();

        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            double dailyRevenue = calculateDailyRevenue(date);
            trendList.add(new DailySalesTrend(date, dailyRevenue));
        }

        return trendList;
    }

    /**
     * 计算某一天的销售收入
     * @param date 日期
     * @return 当日收入
     */
    private double calculateDailyRevenue(LocalDate date) {
        List<Order> orders = orderService.getAllOrders();
        return orders.stream()
            .filter(order -> order.getCreateTime().toLocalDate().equals(date))
            .mapToDouble(Order::getTotalPrice)
            .sum();
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    public UserService getUserService() {
        return userService;
    }

    /**
     * 销售数据统计报告类
     */
    public static class SalesReport {
        private final double totalRevenue;
        private final int totalOrders;
        private final Map<String, Integer> categorySales;
        private final Map<String, Double> productSales;

        public SalesReport(double totalRevenue, int totalOrders, Map<String, Integer> categorySales, Map<String, Double> productSales) {
            this.totalRevenue = totalRevenue;
            this.totalOrders = totalOrders;
            this.categorySales = categorySales;
            this.productSales = productSales;
        }

        // Getters
        public double getTotalRevenue() { return totalRevenue; }
        public int getTotalOrders() { return totalOrders; }
        public Map<String, Integer> getCategorySales() { return categorySales; }
        public Map<String, Double> getProductSales() { return productSales; }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("=== 销售数据统计 ===\n");
            sb.append(String.format("总收入: %.2f\n", totalRevenue));
            sb.append(String.format("总订单数: %d\n", totalOrders));
            sb.append("\n各类别销量:\n");
            for (Map.Entry<String, Integer> entry : categorySales.entrySet()) {
                sb.append(String.format("  %s: %d 件\n", entry.getKey(), entry.getValue()));
            }
            sb.append("\n商品销售情况:\n");
            for (Map.Entry<String, Double> entry : productSales.entrySet()) {
                sb.append(String.format("  %s: %.2f 元\n", entry.getKey(), entry.getValue()));
            }
            return sb.toString();
        }
    }

    /**
     * 用户行为分析报告类
     */
    public static class UserBehaviorAnalysis {
        private final int activeUsers;
        private final double averageOrderValue;
        private final int totalOrders;
        private final Map<String, Integer> popularProducts;
        private final Map<Integer, Integer> purchaseFrequencyDistribution;

        public UserBehaviorAnalysis(int activeUsers, double averageOrderValue, int totalOrders,
                                  Map<String, Integer> popularProducts, Map<Integer, Integer> purchaseFrequencyDistribution) {
            this.activeUsers = activeUsers;
            this.averageOrderValue = averageOrderValue;
            this.totalOrders = totalOrders;
            this.popularProducts = popularProducts;
            this.purchaseFrequencyDistribution = purchaseFrequencyDistribution;
        }

        // Getters
        public int getActiveUsers() { return activeUsers; }
        public double getAverageOrderValue() { return averageOrderValue; }
        public int getTotalOrders() { return totalOrders; }
        public Map<String, Integer> getPopularProducts() { return popularProducts; }
        public Map<Integer, Integer> getPurchaseFrequencyDistribution() { return purchaseFrequencyDistribution; }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("=== 用户行为分析 ===\n");
            sb.append(String.format("活跃用户数: %d\n", activeUsers));
            sb.append(String.format("平均订单金额: %.2f\n", averageOrderValue));
            sb.append(String.format("总订单数: %d\n", totalOrders));
            sb.append("\n热门商品:\n");
            // 按销量排序显示前5个最热门商品
            popularProducts.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(5)
                .forEach(entry -> sb.append(String.format("  %s: %d 件\n", entry.getKey(), entry.getValue())));
            return sb.toString();
        }
    }

    /**
     * 商品销售排行项
     */
    public static class ProductRanking {
        private final int rank;
        private final String productId;
        private final String productName;
        private final int soldQuantity;
        private final double totalSales;

        public ProductRanking(int rank, String productId, String productName, int soldQuantity, double totalSales) {
            this.rank = rank;
            this.productId = productId;
            this.productName = productName;
            this.soldQuantity = soldQuantity;
            this.totalSales = totalSales;
        }

        // Getters
        public int getRank() { return rank; }
        public String getProductId() { return productId; }
        public String getProductName() { return productName; }
        public int getSoldQuantity() { return soldQuantity; }
        public double getTotalSales() { return totalSales; }

        @Override
        public String toString() {
            return String.format("%d. %s (%s) - 销量: %d 件, 销售额: %.2f 元",
                rank, productName, productId, soldQuantity, totalSales);
        }
    }

    /**
     * 财务报表数据类
     */
    public static class FinancialReport {
        private final LocalDate startDate;
        private final LocalDate endDate;
        private final double totalRevenue;
        private final double totalCost;
        private final double netProfit;
        private final List<MonthlyIncome> monthlyIncome;
        private final Map<String, Double> categoryRevenue;

        public FinancialReport(LocalDate startDate, LocalDate endDate, double totalRevenue,
                              double totalCost, double netProfit, List<MonthlyIncome> monthlyIncome,
                              Map<String, Double> categoryRevenue) {
            this.startDate = startDate;
            this.endDate = endDate;
            this.totalRevenue = totalRevenue;
            this.totalCost = totalCost;
            this.netProfit = netProfit;
            this.monthlyIncome = monthlyIncome;
            this.categoryRevenue = categoryRevenue;
        }

        // Getters
        public LocalDate getStartDate() { return startDate; }
        public LocalDate getEndDate() { return endDate; }
        public double getTotalRevenue() { return totalRevenue; }
        public double getTotalCost() { return totalCost; }
        public double getNetProfit() { return netProfit; }
        public List<MonthlyIncome> getMonthlyIncome() { return monthlyIncome; }
        public Map<String, Double> getCategoryRevenue() { return categoryRevenue; }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("=== 财务报表 ===\n");
            sb.append(String.format("统计周期: %s 至 %s\n", startDate, endDate));
            sb.append(String.format("总收入: %.2f\n", totalRevenue));
            sb.append(String.format("总成本: %.2f\n", totalCost));
            sb.append(String.format("净利润: %.2f\n", netProfit));
            sb.append("\n各月收入:\n");
            for (MonthlyIncome income : monthlyIncome) {
                sb.append(String.format("  %s: %.2f\n", income.getMonth(), income.getIncome()));
            }
            sb.append("\n各类别收入:\n");
            for (Map.Entry<String, Double> entry : categoryRevenue.entrySet()) {
                sb.append(String.format("  %s: %.2f\n", entry.getKey(), entry.getValue()));
            }
            return sb.toString();
        }
    }

    /**
     * 每月收入统计类
     */
    public static class MonthlyIncome {
        private final String month;
        private double income;

        public MonthlyIncome(String month) {
            this.month = month;
            this.income = 0.0;
        }

        public void addIncome(double amount) {
            this.income += amount;
        }

        // Getters
        public String getMonth() { return month; }
        public double getIncome() { return income; }
    }

    /**
     * 日销售趋势类
     */
    public static class DailySalesTrend {
        private final LocalDate date;
        private final double revenue;

        public DailySalesTrend(LocalDate date, double revenue) {
            this.date = date;
            this.revenue = revenue;
        }

        // Getters
        public LocalDate getDate() { return date; }
        public double getRevenue() { return revenue; }

        @Override
        public String toString() {
            return String.format("%s: %.2f 元", date, revenue);
        }
    }
}
